package com.tjl.warehouse.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tjl.warehouse.model.AuthInfo;
import com.tjl.warehouse.service.AuthInfoService;
import com.tjl.warehouse.mapper.AuthInfoMapper;
import com.tjl.warehouse.utils.RedisService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author Tang
* @description 针对表【auth_info(权限表)】的数据库操作Service实现
* @createDate 2024-05-18 11:08:26
*/
@Service
public class AuthInfoServiceImpl extends ServiceImpl<AuthInfoMapper, AuthInfo>
    implements AuthInfoService{

    @Resource
    private AuthInfoMapper authInfoMapper;
    @Resource
    RedisService redisService;

    @Override
    public List<AuthInfo> getAuthInfo(Integer userId) {
        //检查redis中是否存在缓存
        if (redisService.hasKey("authInfoTree:" + userId)) {
            String json = redisService.get("authInfoTree:" + userId);
            TypeToken<List<AuthInfo>> typeToken = new TypeToken<>() {};
            return new Gson().fromJson(json,typeToken);
        }
        List<AuthInfo> authInfo = authInfoMapper.getAuthInfo(userId);
        List<AuthInfo> authTreeList = allAuthInfoTree(authInfo, 0);

        //存入redis
        redisService.set("authInfoTree:" + userId,new Gson().toJson(authTreeList),180);
        return authTreeList;

    }

    //将所有权限菜单转换成权限菜单树
    private List<AuthInfo> allAuthInfoTree(List<AuthInfo> allAuthList, Integer parentId) {
        //创建空的List集合对象
        List<AuthInfo> authList = new ArrayList<>();
        //通过循环遍历的方式来获取所有的一级权限菜单
        for(AuthInfo auth:allAuthList){
            if(auth.getParentId() == parentId){
                //该集合中保存的是所有的一级权限菜单
                authList.add(auth);
            }
        }
        //根据已经获取到的一级权限菜单，来获取对应的二级权限菜单
        for(AuthInfo auth:authList){
            //回调函数
            //获取到所有的二级权限菜单
            List<AuthInfo> childAuthList = allAuthInfoTree(allAuthList,auth.getAuthId());
            auth.setChildAuth(childAuthList);
        }
        //返回一级权限菜单的list
        return authList;
    }
}




